package com.qfedu.lc.server.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qfedu.lc.common.config.RedisKeyConfig;
import com.qfedu.lc.common.param.UserAdd;
import com.qfedu.lc.common.util.StrUtil;
import com.qfedu.lc.common.vo.R;
import com.qfedu.lc.server.dao.UserDao;
import com.qfedu.lc.server.dao.UserLogDao;
import com.qfedu.lc.server.entity.User;
import com.qfedu.lc.server.entity.UserLog;
import com.qfedu.lc.server.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 1.用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-10-19 14:19:50
 */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao dao;
    @Resource
    private UserLogDao logDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public R save(UserAdd add,String ip) {
        //1.校验参数
        if(add!=null && StrUtil.isNotEmpty(add.getAccount(),add.getPhone(),add.getPassword())){
            //2.校验是否存在短信验证码
            String key=RedisKeyConfig.SMS_RCODE+add.getPhone();
            if(redisTemplate.hasKey(key)){
                //3.验证账号是否存在
                if(dao.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount,add.getAccount()))==null){
                    //4.校验 短信验证码
                    if(add.getCode().equals(redisTemplate.opsForValue().get(key))){
                        //5.验证码成功 准备对象 新增用户
                        User user=new User();
                        user.setAccount(add.getAccount());
                        user.setPhone(add.getPhone());
                        user.setPassword(SecureUtil.sha256(SecureUtil.md5(add.getPassword())));
                        user.setStatus(1);
                        user.setCtime(new Date());
                        if(dao.insert(user)>0){
                            //6.验证码 删除
                            redisTemplate.delete(key);

                            //7.新增日志
                            logDao.insert(new UserLog(user.getId(),"注册",ip,"注册新用户",add.getMobile()));
                            //8.新人有礼 待定

                            return R.ok();
                        }

                    }else {
                        return R.fail("亲，能不能检查一下验证码！");
                    }

                }else {
                    return R.fail("亲，账号已存在，请重新设置");
                }

            }else {
                return R.fail("亲，请先发送短信验证码!");
            }
        }
        return R.fail("注册失败！");
    }

    @Override
    public R all() {
        return R.ok(dao.selectList(null));
    }
}

